package com.three.crm.page.common;


import android.Manifest;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.three.crm.R;
import com.three.crm.adapter.CallLogAdapter;
import com.three.crm.adapter.VisitListAdapter;
import com.three.crm.base.BaseActivity;
import com.three.crm.bean.CallLogBean;
import com.three.crm.constant.AppConstant;
import com.three.crm.util.DateUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class CallLogActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks{

    private EditText etInput;
    private ImageView ivAdd;
    private TextView tvLoading,tvTitle;
    private View mLoadingView;
    private ImageView ivState;
    private ProgressBar progressBar;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private CallLogAdapter adapter;

    private List<CallLogBean> callLogList = new ArrayList<>();

    public final static String[] PERMISSES = {
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_PHONE_STATE
    };
    private boolean hasPermiss = false;

    @Override
    protected void initParms(Bundle bundle) {

    }

    @Override
    protected int bindLayout() {
        return R.layout.common_list_layout;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        tvTitle = $(R.id.tv_title);
        tvTitle.setText("通话记录");

        etInput = $(R.id.et_input);
        etInput.setVisibility(View.GONE);
        refreshLayout = $(R.id.refresh_layout);
        mLoadingView = LayoutInflater.from(this).inflate(R.layout.loading_view,null);
        ivState = mLoadingView.findViewById(R.id.iv_state);
        tvLoading = mLoadingView.findViewById(R.id.tv_loading);
        progressBar = mLoadingView.findViewById(R.id.progressBar);

        recyclerView = $(R.id.recycleview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new CallLogAdapter();
        recyclerView.setAdapter(adapter);

        onCheckPermission();
    }

    private void onCheckPermission() {
        if (EasyPermissions.hasPermissions(this,PERMISSES)){
            hasPermiss = true;
            onLoadCallLog();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.app_name) + "需要获取通讯录等权限，您是否同意?",
                    AppConstant.RC_PERMISSES, PERMISSES);
        }
    }

    @Override
    protected void setListener() {
        $(R.id.iv_left).setOnClickListener(this);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onLoadCallLog();
            }
        });
        tvLoading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLoadCallLog();
            }
        });
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()){
            case R.id.iv_left:
                finish();
                break;
        }
    }

    @Override
    protected void initData(Context mContext) {

    }

    private void onLoadCallLog() {
        callLogList.clear();
        if (refreshLayout != null && refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(true);
        }
        progressBar.setVisibility(View.VISIBLE);
        tvLoading.setText(getString(R.string.loading));
        ivState.setVisibility(View.GONE);
        adapter.setEnableLoadMore(true);
        adapter.getData().clear();
        adapter.setEmptyView(mLoadingView);

        Cursor cs = this.getContentResolver().query(CallLog.Calls.CONTENT_URI, //系统方式获取通讯录存储地址
                new String[]{
                        CallLog.Calls.NUMBER,    //号码
                        CallLog.Calls.DATE,  //拨打时间
                        CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                        CallLog.Calls.DURATION,   //通话时长
                }, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);

        if (cs == null) {
            resetRefresh();
            adapter.loadMoreEnd();
            adapter.setEnableLoadMore(false);
            setState(getString(R.string.no_data),R.mipmap.ic_empty);
        } else {
            while (cs.moveToNext()) {
                String number = cs.getString(0);
                long date = cs.getLong(1);
                int type = cs.getInt(2);
                int duration = cs.getInt(3);

                if (DateUtils.getToday().equals(DateUtils.getDateByTime(date))) {
                    String callTypeStr = "";
                    if (type == CallLog.Calls.INCOMING_TYPE) {
                        callTypeStr = "来电";
                    } else if (type == CallLog.Calls.OUTGOING_TYPE){
                        callTypeStr = "去电";
                    } else if (type == CallLog.Calls.MISSED_TYPE){
                        callTypeStr = "未接听";
                    } else {
                        callTypeStr = "未知";
                    }

                    CallLogBean callLogBean = new CallLogBean();
                    callLogBean.setContactName(number);
                    callLogBean.setCallDateStr(DateUtils.getTime(date));
                    callLogBean.setCallTypeStr(callTypeStr);
                    callLogBean.setCallNumber(number);
                    callLogBean.setCallDurationStr(String.valueOf(duration));
                    callLogList.add(callLogBean);
                }
            }
            cs.close();
            resetRefresh();
            if (callLogList.size() == 0) {
                adapter.loadMoreEnd();
                adapter.setEnableLoadMore(false);
                setState(getString(R.string.no_data),R.mipmap.ic_empty);
            } else {
                adapter.setNewData(callLogList);
                adapter.loadMoreComplete();
                adapter.loadMoreEnd();
                adapter.setEnableLoadMore(false);
            }
        }


        Log.i("TAG","callLogList="+callLogList.size());

//        int i = 0;
//        if (cs != null && cs.getCount() > 0) {
//
//            Date date = new Date(System.currentTimeMillis());
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            String date_today = simpleDateFormat.format(date);
//
//            for (cs.moveToFirst(); (!cs.isAfterLast()); cs.moveToNext(), i++) {
//                String callName = cs.getString(0);  //名称
//                String callNumber = cs.getString(1);  //号码
//                //如果名字为空，在通讯录查询一次有没有对应联系人
//                if (callName == null || callName.equals("")){
//                    String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME};
//                    //设置查询条件
//                    String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + "='"+callNumber+"'";
//                    Cursor cursor = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
//                            cols, selection, null, null);
//                    int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
//                    if (cursor.getCount()>0){
//                        cursor.moveToFirst();
//                        callName = cursor.getString(nameFieldColumnIndex);
//                    }
//                    cursor.close();
//                }
//                //通话类型
//                int callType = Integer.parseInt(cs.getString(2));
//                String callTypeStr = "";
//                switch (callType) {
//                    case CallLog.Calls.INCOMING_TYPE:
//                        callTypeStr = "打进来";
//                        break;
//                    case CallLog.Calls.OUTGOING_TYPE:
//                        callTypeStr = "打出去";
//                        break;
//                    case CallLog.Calls.MISSED_TYPE:
//                        callTypeStr = "未接听";
//                        break;
//                    default:
//                        //其他类型的，例如新增号码等记录不算进通话记录里，直接跳过
//                        Log.i("ssss",""+callType);
//                        i--;
//                        continue;
//                }
//                //拨打时间
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//                Date callDate = new Date(Long.parseLong(cs.getString(3)));
//                String callDateStr = sdf.format(callDate);
//                if (callDateStr.equals(date_today)) { //判断是否为今天
//                    sdf = new SimpleDateFormat("HH:mm");
//                    callDateStr = sdf.format(callDate);
//                } else if (date_today.contains(callDateStr.substring(0, 7))) { //判断是否为当月
//                    sdf = new SimpleDateFormat("dd");
//                    int callDay = Integer.valueOf(sdf.format(callDate));
//
//                    int day = Integer.valueOf(sdf.format(date));
//                    if (day - callDay == 1) {
//                        callDateStr = "昨天";
//                    } else {
//                        sdf = new SimpleDateFormat("MM-dd");
//                        callDateStr = sdf.format(callDate);
//                    }
//                } else if (date_today.contains(callDateStr.substring(0, 4))) { //判断是否为当年
//                    sdf = new SimpleDateFormat("MM-dd");
//                    callDateStr = sdf.format(callDate);
//                }
//
//                //通话时长
//                int callDuration = Integer.parseInt(cs.getString(4));
//                int min = callDuration / 60;
//                int sec = callDuration % 60;
//                String callDurationStr = "";
//                if (sec > 0) {
//                    if (min > 0) {
//                        callDurationStr = min + "分" + sec + "秒";
//                    } else {
//                        callDurationStr = sec + "秒";
//                    }
//                }
//
//                /**
//                 * callName 名字
//                 * callNumber 号码
//                 * callTypeStr 通话类型
//                 * callDateStr 通话日期
//                 * callDurationStr 通话时长
//                 * 请在此处执行相关UI或存储操作，之后会查询下一条通话记录
//                 */
//                Log.i("Msg","callName"+callName);
//                Log.i("Msg","callNumber"+callNumber);
//                Log.i("Msg","callTypeStr"+callTypeStr);
//                Log.i("Msg","callDateStr"+callDateStr);
//                Log.i("Msg","callDurationStr"+callDurationStr);
//
//                CallLogBean callLogBean = new CallLogBean(callName,callNumber,callTypeStr,callDateStr,callDurationStr);
//                callLogList.add(callLogBean);
//            }
//        }

        //

    }

    private void setState(String string, int resId) {
        progressBar.setVisibility(View.GONE);
        tvLoading.setText(string);
        ivState.setImageResource(resId);
        ivState.setVisibility(View.VISIBLE);
        adapter.setEmptyView(mLoadingView);
        adapter.notifyDataSetChanged();
    }

    private void resetRefresh() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(false);
        }
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resetRefresh();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        hasPermiss = true;
        onLoadCallLog();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {

    }

    @Override
    public void onRationaleDenied(int requestCode) {
        showToast("好伤心，您将无法使用通讯录等相关功能");
    }
}